package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private IStrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    public void saveOrUpdate(StrategyComment strategyComment) {
        if(!StringUtils.hasLength(strategyComment.getId())){
            //创建时间
            strategyComment.setCreateTime(new Date());
        }
        repository.save(strategyComment);
    }

    public Page query(StrategyCommentQuery qo) {
        //查询条件
        Query query = new Query();
        if(qo.getDetailId() != -1){
            //限制条件
            Criteria criteria = Criteria.where("detailId").is(qo.getDetailId());
            query.addCriteria(criteria);
        }
        //查询总条数
        long count = template.count(query, StrategyComment.class);
        if(count == 0){
            return Page.empty();
        }
        //分页查询对象
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.by(Sort.Direction.DESC, "createTime"));
        query.with(pageable);
        //查询符合条件的数据
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,count);
    }

    public void commentThumbUp(String commentId, Long userId) {
        StrategyComment strategyComment = repository.findById(commentId).get();
        //如果用户在点赞集合中
        if(strategyComment.getThumbuplist().contains(userId)){
            //点赞数-1
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
            //点赞集合移除用户
            strategyComment.getThumbuplist().remove(userId);
        }else{  //如果用户不在点赞集合中
            //点赞数+1
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
            //点赞集合加入用户
            strategyComment.getThumbuplist().add(userId);
        }
        //更新该攻略评论
        repository.save(strategyComment);
    }
}
